/******************************************************************************
 * @File name   :      MaintainMemberController.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 20, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 20, 2015 7:03:02 PM    ANMA      1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.card.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.card.domain.CardDefinition;
import com.cap.bts.crmdp.dealer.card.domain.CardGeneration;
import com.cap.bts.crmdp.dealer.card.dto.CardCreateResultsDto;
import com.cap.bts.crmdp.dealer.card.dto.CardDefineQueryDto;
import com.cap.bts.crmdp.dealer.card.dto.CardDefineResultsDto;
import com.cap.bts.crmdp.dealer.card.dto.CardDefineSubmitDto;
import com.cap.bts.crmdp.dealer.card.dto.CardExportDto;
import com.cap.bts.crmdp.dealer.card.service.ICardCreateService;
import com.cap.bts.crmdp.dealer.card.service.ICardDefineService;
import com.cap.bts.crmdp.dealer.card.service.ICardExportService;
import com.cap.bts.crmdp.dealer.card.util.FileUtil;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;

/**
 * 
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/card")
public class CardController extends BaseController {

    private static final  Logger LOGGER  = Logger.getLogger(CardController.class);
    @Autowired
    ICardDefineService cardDefineService;
    @Autowired
    ICardCreateService cardCreateService;
    @Autowired
    ICardExportService cardExportService;
    @Autowired
    IMemberPackageService memberPackageService;
    
    /**
     * 创建会员卡主页面
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toCreateCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/toCreateCard")
    public String toCreateCard(Model model, HttpServletRequest request)
        throws AppException {
        List<CardCreateResultsDto> list=cardCreateService.findAllCardGenerationList();
        model.addAttribute("CardCreateResultsListDto", list);
        return "/card/createCard";
    }
    
    /**
     * 创建会员卡主页面
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toCreateCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/getCardNumTo")
    @ResponseBody
    public CardCreateResultsDto getCardNumTo(Long id,Integer quantity,Model model, HttpServletRequest request)
        throws AppException {
        CardCreateResultsDto rtnDto=new CardCreateResultsDto();
        String cardNumStr="";
        String msg="";
        Integer rtnQuantity=cardCreateService.getGenerateQuantity(id,quantity);
        if(rtnQuantity.equals(quantity)){
           cardNumStr=cardCreateService.getCardNumTo(id, quantity);
           rtnDto.setQuantity(quantity);
           rtnDto.setCardNumTo(cardNumStr);
        }else{
            msg="生成数量大于卡号最大位数，可生成数量为"+rtnQuantity.toString();
            rtnDto.setQuantity(rtnQuantity);
            rtnDto.getBaseDto().setErrorMsg(msg);
        }
        return rtnDto; 
    }
    
    /**
     * 生成会员卡
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toCreateCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/generateCard")
    @ResponseBody
    public boolean generateCard(Integer[] id,Integer[] quantity,Model model, HttpServletRequest request)
        throws AppException {
        boolean rtn=true;
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<id.length;i++){
            if(quantity[i]!=null&&quantity[i]!=0){
                sb.append(id[i].toString());
                sb.append("_");
                sb.append(quantity[i].toString());
                sb.append("_");
                sb.append(UserUtil.getCurrentUser().getId());
                sb.append(",");
                LOGGER.info(sb.toString());
            }
        }
        LOGGER.info(sb.toString());
        sb.deleteCharAt(sb.length()-1);
        rtn=cardCreateService.generateCard(sb.toString());
        return rtn;
    }
    
    /**
     * 查询会员卡名字是否存在
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toCreateCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/isCardNameExsit")
    @ResponseBody
    public boolean isCardNameExsit(Long id,String name,Model model, HttpServletRequest request)
        throws AppException {
        LOGGER.info("id:"+id+",quantity:"+name);
        boolean rtn=cardCreateService.isCardNameExsit(id, name);
        LOGGER.info("return:"+rtn);
        return rtn;
    }
    
    /**
     * 
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toCreateCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/getCardDefinitionCount")
    @ResponseBody
    public Integer getCardDefinitionCount(CardDefineQueryDto dto,Model model, HttpServletRequest request)
        throws AppException {
        Integer rtn=cardDefineService.getCardDefinitionCount(dto);
        LOGGER.info("return:"+rtn);
        return rtn;
    }
    
    
    /**
     * 
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toCreateCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/checkExsitUsedCardInfo")
    @ResponseBody
    public Map<String,String> checkExsitUsedCardInfo(CardDefineQueryDto dto,Model model, HttpServletRequest request)
        throws AppException {
        Map<String,String> rtnMap=new HashMap<String,String>();
        MemberPackageInfo mpi=null;
        String rtn="";
        if(dto.getPerfix()!=null){
                mpi=memberPackageService.getMaxMemberPackageInfoByNonPhysicalCardPrefix(dto.getPerfix());
            }
        
        if(mpi!=null){
           rtn="该前缀的卡号已经在使用中,最新卡号："+mpi.getPackageNumber()+",确认卡片设定与使用中卡号是否一致,继续添加请点击确定按钮,添加后的卡片定义将直接进入启用状态!";
           rtnMap.put("rtnPackageNumber", mpi.getPackageNumber());
        }
        rtnMap.put("rtnInfo", rtn);
        return rtnMap;
    }
    
    
    /**
     * 显示会员卡定义页面
     * 
     * @Date : 2015-7-15
     * @param dto
     *            CardDefineQueryDto
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/toDefineCard")
    public String toDefineCard(CardDefineQueryDto dto, Model model, HttpServletRequest request)
        throws AppException {
        List<CardDefinition> list = cardDefineService.getCardDefinitionListByDto(dto);
        CardDefineResultsDto resultDto = new CardDefineResultsDto();
        resultDto.setCardDefineList(list);
        resultDto.setQueryStatus(dto.getQueryStatus());
        model.addAttribute("CardDefineResultsDto", resultDto);
        model.addAttribute("CardDefineQueryDto", dto);
        model.addAttribute("QueryStatus", dto.getQueryStatus());
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "/card/defineCard";
    }

    /**
     * 删除会员卡
     * 
     * @Date : 2015-7-15
     * @param dto
     *            CardDefineSubmitDto
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/deleteCard")
    public String deleteCard(CardDefineSubmitDto dto, Model model, HttpServletRequest request)
        throws AppException {
        CardDefineQueryDto qDto = new CardDefineQueryDto();
        qDto.setPager(dto.getPager());
        qDto.setQueryStatus(dto.getQueryStatus());
        cardDefineService.deleteCardDefinition(dto);
        return toDefineCard(qDto, model, request);
    }

    /**
     * 添加会员卡
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toDefineCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/addCard")
    public String addCard(CardDefineSubmitDto dto, Model model, HttpServletRequest request)
        throws AppException {
        cardDefineService.addCardDefinition(dto);
        CardDefineQueryDto qDto = new CardDefineQueryDto();
        qDto.setQueryStatus(dto.getQueryStatus());
        return toDefineCard(qDto, model, request);
    }

    /**
     * 修改会员卡
     * 
     * @Date : 2015-7-15
     * @param dto
     *            modifyCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/modifyCard")
    public String modifyCard(CardDefineSubmitDto dto, Model model, HttpServletRequest request)
        throws AppException {
        CardDefineQueryDto qDto = new CardDefineQueryDto();
        qDto.setPager(dto.getPager());
        qDto.setQueryStatus(dto.getQueryStatus());
        cardDefineService.updateCardDefinition(dto);
        return toDefineCard(qDto, model, request);
    }
    
    /**
     * 导出会员卡页面
     * 
     * @Date : 2015-7-15
     * @param dto
     *            toExportCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String   
     * @throws Exception
     */
    @RequestMapping(value = "/toExportCard")
    public String toExportCard(CardExportDto dto, Model model, HttpServletRequest request)
        throws AppException {
        List<CardGeneration> list=cardExportService.getExportCardListByQueryDto(dto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        model.addAttribute("dto", dto);
        model.addAttribute("cardGenerationList", list);
        return "/card/exportCard";
    }
    
    /**
     * 会员卡导出
     * 
     * @Date : 2015-7-15
     * @param dto
     *            exportCard
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String   
     * @throws Exception
     */
    @RequestMapping(value = "/exportCard")
    public String exportCard(CardExportDto dto, Model model, HttpServletRequest request, HttpServletResponse response)
        throws AppException {
        List<File> files=cardExportService.generateCSVfile(dto.getExportList());
        try {
            FileUtil.downloadZip(files.get(0),response,request);
        } catch (Exception e) {
            throw new AppException("exportCard",e);
        }
        return "/card/exportCard";
    }
}
